package logic

import (
	"context"
	"errors"
	"video/mysql/cache"
	"video/mysql/model"

	"video/videorpc/internal/svc"
	"video/videorpc/videorpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type UpdatePasswordLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewUpdatePasswordLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UpdatePasswordLogic {
	return &UpdatePasswordLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// 密码重置
func (l *UpdatePasswordLogic) UpdatePassword(in *videorpc.UpdatePasswordRequest) (*videorpc.UpdatePasswordResponse, error) {
	// todo: add your logic here and delete this line

	var user model.User
	model.DB.Debug().Where("account = ?", in.Account).Find(&user)
	if user.ID == 0 {
		return nil, errors.New("当前账号不存在,无重置密码")
	}

	if in.Password != in.NewPassword {
		return nil, errors.New("两次输入的密码不一致,修改失败")
	}

	if in.Password == user.Password {
		return nil, errors.New("新密码和旧密码一致,修改失败")
	}

	result, _ := cache.Rdb.Get(l.ctx, "sendSms"+in.Account).Result()
	if result != in.SendSms {
		return nil, errors.New("短信验证码错误,密码修改失败")
	}

	user.Password = in.Password
	model.DB.Debug().Updates(&user)

	return &videorpc.UpdatePasswordResponse{
		UserId: int64(user.ID),
	}, nil
}
